<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-container>
        <el-row style="width:100%">
            <el-col :span="4">
                <el-input placeholder="请输入消息内容" v-model="msgData"></el-input>
            </el-col>
            <el-col :span="4">
                <el-button @click="sendMessage" type="primary" style="margin-left:10px;">发送</el-button>
                <el-button @click="openConnect">连接</el-button>
                <el-button @click="closeConnect">关闭连接</el-button>
            </el-col>
            <el-col :span="16">
                <el-input
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 10}"
                        placeholder="连接日志"
                        v-model="logData">
                </el-input>
            </el-col>
        </el-row>
    </el-container>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    axios.defaults.baseURL = "http://localhost:8881/apg";
    axios.defaults.headers['Content-Type'] = 'application/json';
    new Vue({
        el: '#app',
        data: function () {
            return {
                webSocket: null,
                logData: '',
                msgData: ''
            }
        },
        methods: {
            sendMessage() {
                this.webSocket.send(this.msgData)
            },
            closeConnect() {
                this.webSocket.close()
                this.webSocket = null
            },
            openConnect(){
                if(this.webSocket !== null){
                    this.$message.error('请先关闭webSocket连接');
                    return
                }
                if(!'WebSocket' in window){
                    this.$message.error('该浏览器不支持webSocket');
                }else{
                    this.webSocket = new WebSocket("ws://localhost:8881/apg/ws")
                }
            }
        },
        mounted () {
            that = this
            this.openConnect()
            this.webSocket.onopen = function(event){
                that.logData+="连接成功\n"
            }
            this.webSocket.onerror = function(){
                that.logData+="连接错误\n"
            }
            this.webSocket.onclose = function(){
                that.logData+="连接关闭\n"
            }
            // 窗口关闭时关闭连接
            window.onBeforeunload = function () {
                that.webSocket.close()
            }
            this.webSocket.onmessage = function(event){
                that.logData+=event.data+"\n"
            }
        }
    })
</script>
</html>